#!/bin/bash

# PrestaShop 9.0.1 企业版自动安装脚本 - Ubuntu 24.04 + Apache
set -e

echo "=========================================="
echo "    PrestaShop 9.0.1 企业版安装脚本"
echo "    Ubuntu 24.04 + Apache + MySQL"
echo "=========================================="

# 配置变量
DOMAIN="successon.org"  # 请修改为你的域名或服务器IP
EMAIL="admin@successon.org"
PS_VERSION="9.0.1"
PS_PACKAGE_URL="https://assets.prestashop3.com/dst/edition/corporate/9.0.1-1.0/prestashop_edition_basic_version_9.0.1-1.0.zip?token=9c3095b0a0"
DB_NAME="prestashop9_db"
DB_USER="prestashop9_user"
DB_PASS=$(openssl rand -base64 12)
ADMIN_PASS=$(openssl rand -base64 12)
PS_DIR="/var/www/prestashop9"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}

warning() {
    echo -e "${YELLOW}[警告] $1${NC}"
}

error() {
    echo -e "${RED}[错误] $1${NC}"
    exit 1
}

# 检查 root 权限


# 更新系统
update_system() {
    log "更新系统包..."
    sudo apt update && sudo apt upgrade -y
}

# 安装必要的工具
install_tools() {
    log "安装必要工具..."
    sudo apt install -y wget curl gnupg software-properties-common unzip
}

# 安装 Apache
install_apache() {
    log "安装 Apache..."
    sudo apt install -y apache2
    
    log "启用 Apache 模块..."
    sudo a2enmod rewrite
    sudo a2enmod ssl
    sudo a2enmod headers
    sudo a2enmod expires
    
    sudo systemctl enable apache2
    sudo systemctl start apache2
}
 
# 安装 MySQL 8.0
install_mysql() {
    log "安装 MySQL..."
    sudo apt install -y mysql-server mysql-client
    
    sudo systemctl enable mysql
    sudo systemctl start mysql
    
    # 安全配置
    log "执行 MySQL 安全配置..."
    sudo mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '';"
    
    # 自动安全配置
    sudo mysql_secure_installation <<EOF
n
y
y
y
y
EOF
}

# 配置数据库
setup_database() {
    log "创建 PrestaShop 9.0 数据库..."
    
    # 创建数据库和用户
    sudo mysql -e "CREATE DATABASE IF NOT EXISTS $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
    sudo mysql -e "CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';"
    sudo mysql -e "GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost';"
    sudo mysql -e "FLUSH PRIVILEGES;"
    
    log "数据库配置完成！"
    echo "数据库名: $DB_NAME" | tee -a prestashop9_credentials.txt
    echo "数据库用户: $DB_USER" | tee -a prestashop9_credentials.txt
    echo "数据库密码: $DB_PASS" | tee -a prestashop9_credentials.txt
}

# 下载 PrestaShop 9.0.1 企业版
download_prestashop() {
    log "下载 PrestaShop $PS_VERSION 企业版..."
    
    # 创建安装目录
    sudo mkdir -p $PS_DIR
    sudo chown -R $USER:$USER $PS_DIR
    
    cd /tmp
    if [ -f "prestashop9.zip" ]; then
        rm prestashop9.zip
    fi
    
    log "从官方链接下载..."
    wget -O prestashop9.zip "$PS_PACKAGE_URL"
    
    if [ ! -f "prestashop9.zip" ]; then
        error "下载 PrestaShop 9.0.1 失败！"
    fi
    
    # 检查文件大小
    file_size=$(stat -c%s "prestashop9.zip")
    if [ $file_size -lt 1000000 ]; then
        error "下载的文件可能不完整，文件大小: $file_size 字节"
    fi
    
    log "解压 PrestaShop 9.0.1..."
    unzip -q prestashop9.zip -d $PS_DIR/
    
    # 检查解压结果
    if [ ! -f "$PS_DIR/index.php" ]; then
        error "解压失败或文件结构不正确"
    fi
    
    log "PrestaShop 9.0.1 文件解压完成"
}

# 设置文件权限
set_permissions() {
    log "设置文件权限..."
    
    # 更改所有者给 www-data
    sudo chown -R www-data:www-data $PS_DIR
    
    # 设置目录权限
    sudo find $PS_DIR -type d -exec chmod 755 {} \;
    sudo find $PS_DIR -type f -exec chmod 644 {} \;
    
    # PrestaShop 9.x 需要的可写目录
    writable_dirs=(
        "var/cache"
        "var/logs"
        "var/sessions"
        "img"
        "mails"
        "modules"
        "themes"
        "translations"
        "upload"
        "download"
        "config"
    )
    
    for dir in "${writable_dirs[@]}"; do
        if [ -d "$PS_DIR/$dir" ]; then
            sudo chmod -R 775 "$PS_DIR/$dir"
            sudo chown -R www-data:www-data "$PS_DIR/$dir"
        fi
    done
    
    # 特殊处理 config 目录
    if [ -d "$PS_DIR/config" ]; then
        sudo chmod 775 "$PS_DIR/config"
        sudo chown -R www-data:www-data "$PS_DIR/config"
    fi
}

# 配置 Apache 虚拟主机
setup_apache_vhost() {
    log "配置 Apache 虚拟主机..."
    
    # 创建虚拟主机配置
    sudo tee /etc/apache2/sites-available/prestashop9.conf > /dev/null <<EOF
<VirtualHost *:80>
    ServerName $DOMAIN
    ServerAdmin $EMAIL
    DocumentRoot $PS_DIR

    <Directory $PS_DIR>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
        
        # PrestaShop 9.x 安全设置
        <Files "*.tpl">
            Require all denied
        </Files>
        
        <Files "*.log">
            Require all denied
        </Files>
        
        <Files "*.sql">
            Require all denied
        </Files>
    </Directory>

    # 错误日志
    ErrorLog \${APACHE_LOG_DIR}/prestashop9_error.log
    CustomLog \${APACHE_LOG_DIR}/prestashop9_access.log combined

    # 性能优化 - PrestaShop 9.x
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType font/woff "access plus 1 year"
    ExpiresByType font/woff2 "access plus 1 year"
</VirtualHost>
EOF

    # 启用站点
    sudo a2ensite prestashop9.conf
    sudo a2dissite 000-default.conf
    
    # 测试配置
    if ! sudo apache2ctl configtest; then
        error "Apache 配置测试失败，请检查配置"
    fi
    
    log "重启 Apache..."
    sudo systemctl restart apache2
}

# 配置 PHP 8.3 优化
setup_php() {
    log "配置 PHP 8.3 优化..."
    
    PHP_INI_FILE="/etc/php/8.3/apache2/php.ini"
    
    if [ ! -f "$PHP_INI_FILE" ]; then
        error "PHP 8.3 配置文件不存在: $PHP_INI_FILE"
    fi
    
    # 备份原始配置
    sudo cp "$PHP_INI_FILE" "${PHP_INI_FILE}.backup"
    
    # PrestaShop 9.x 推荐的 PHP 配置
    log "优化 PHP 配置..."
    sudo sed -i 's/memory_limit = .*/memory_limit = 512M/' "$PHP_INI_FILE"
    sudo sed -i 's/upload_max_filesize = .*/upload_max_filesize = 100M/' "$PHP_INI_FILE"
    sudo sed -i 's/post_max_size = .*/post_max_size = 100M/' "$PHP_INI_FILE"
    sudo sed -i 's/max_execution_time = .*/max_execution_time = 300/' "$PHP_INI_FILE"
    sudo sed -i 's/max_input_time = .*/max_input_time = 300/' "$PHP_INI_FILE"
    sudo sed -i 's/max_input_vars = .*/max_input_vars = 5000/' "$PHP_INI_FILE"
    
    # OpCache 优化
    sudo sed -i 's/opcache.enable=.*/opcache.enable=1/' "$PHP_INI_FILE"
    sudo sed -i 's/opcache.memory_consumption=.*/opcache.memory_consumption=256/' "$PHP_INI_FILE"
    sudo sed -i 's/opcache.max_accelerated_files=.*/opcache.max_accelerated_files=20000/' "$PHP_INI_FILE"
    
    sudo systemctl restart apache2
    log "PHP 配置优化完成"
}

# 安装 SSL 证书（可选）
install_ssl() {
    log "安装 SSL 证书工具..."
    
    sudo apt install -y certbot python3-certbot-apache
    
    read -p "是否要安装 SSL 证书？(需要域名已解析)(y/n): " install_ssl
    if [[ $install_ssl == "y" ]]; then
        log "安装 SSL 证书..."
        sudo certbot --apache -d $DOMAIN --email $EMAIL --agree-tos --redirect --non-interactive
    else
        log "跳过 SSL 证书安装"
    fi
}

# 创建管理员账户脚本
create_admin_script() {
    log "创建管理员账户设置脚本..."
    
    cat > "$PS_DIR/create_admin.php" << 'EOF'
<?php
/**
 * PrestaShop 管理员创建脚本
 * 访问: http://your-domain.com/create_admin.php
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';
    
    if (!empty($email) && !empty($password)) {
        // 这里需要根据实际安装后的情况调整
        // 这只是一个示例脚本
        echo "管理员账户创建功能需要在安装后手动配置";
    }
} else {
?>
<!DOCTYPE html>
<html>
<head>
    <title>创建管理员账户</title>
</head>
<body>
    <h2>PrestaShop 管理员账户设置</h2>
    <form method="POST">
        <p>邮箱: <input type="email" name="email" required></p>
        <p>密码: <input type="password" name="password" required></p>
        <p><button type="submit">创建管理员</button></p>
    </form>
</body>
</html>
<?php
}
EOF
    
    sudo chown www-data:www-data "$PS_DIR/create_admin.php"
    sudo chmod 644 "$PS_DIR/create_admin.php"
}

# 显示安装信息
show_installation_info() {
    log "PrestaShop 9.0.1 企业版安装完成！"
    echo ""
    echo "================== 安装信息 =================="
    echo "PrestaShop 版本: 9.0.1 企业版"
    echo "网站目录: $PS_DIR"
    echo "访问地址: http://$DOMAIN"
    echo "数据库名: $DB_NAME"
    echo "数据库用户: $DB_USER"
    echo "数据库密码: $DB_PASS"
    echo "推荐管理员密码: $ADMIN_PASS"
    echo ""
    echo "安装步骤:"
    echo "1. 通过浏览器访问 http://$DOMAIN"
    echo "2. 按照安装向导完成设置"
    echo "3. 使用上面的数据库信息"
    echo "4. 安装完成后删除 install 目录"
    echo ""
    echo "系统要求检查:"
    echo "- PHP 8.1-8.3: ✓"
    echo "- MySQL 5.7+ / MariaDB 10.4+: ✓"
    echo "- Apache with mod_rewrite: ✓"
    echo "=============================================="
    
    # 保存凭据到文件
    cat > prestashop9_credentials.txt <<EOF
PrestaShop 9.0.1 企业版安装凭据
================================
安装地址: http://$DOMAIN
网站目录: $PS_DIR

数据库信息:
- 主机: localhost
- 数据库名: $DB_NAME
- 用户名: $DB_USER
- 密码: $DB_PASS

安装完成后请执行:
1. 删除 $PS_DIR/install 目录
2. 删除 $PS_DIR/create_admin.php (如果存在)
3. 配置管理员账户和安全设置
4. 备份数据库和文件

系统信息:
- Ubuntu 24.04 LTS
- Apache 2.4
- PHP 8.3
- MySQL 8.0
EOF
    
    log "详细凭据已保存到: $(pwd)/prestashop9_credentials.txt"
}

# 主安装函数
main() {
    log "开始安装 PrestaShop 9.0.1 企业版..."
    update_system
    install_tools
    install_apache
    install_php
    install_mysql
    setup_database
    download_prestashop
    set_permissions
    setup_apache_vhost
    setup_php
    create_admin_script
    install_ssl
    show_installation_info
    
    log "PrestaShop 9.0.1 安装脚本执行完成！"
    log "请通过浏览器访问 http://$DOMAIN 完成安装"
}

# 执行主函数
main "$@"